package com.tina.shiro;

import com.tina.entity.TiMenu;
import com.tina.entity.TiRole;
import com.tina.entity.TiUsers;
import com.tina.service.TiUsersService;
import com.tina.util.SystemUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author PIGS-猪农·杨
 * @version 1.0
 * @date 2020/3/18 22:25
 * @effect
 */
public class UserRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    private TiUsersService tiUsersService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        TiUsers tiUsers = (TiUsers) principalCollection.getPrimaryPrincipal();

        /**
         * 通过遍历，将user对象中的角色和权限都打包到info对象中
         */
        for (TiRole tiRole : tiUsers.getTiRoleList()) {
            /**
             * 将角色名存到角色中
             */
            if (SystemUtils.isEmpty(tiRole.getRoleName())) {
                authorizationInfo.addRole(tiRole.getRoleName());
            }
            for (TiMenu p : tiRole.getTiMenuList()) {
                /**
                 * 将数据表中的权限“user:add”存到info中
                 */
                if (SystemUtils.isEmpty(p.getPerms())) {
                    authorizationInfo.addStringPermission(p.getPerms());
                }

            }
        }
        return authorizationInfo;
    }


    /**
     * 认证信息
     *
     * @param authenticationToken
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String) authenticationToken.getPrincipal();

        TiUsers tiUsers = tiUsersService.queryByName(userName);

        if (tiUsers == null) {
            throw new UnknownAccountException("不知道这个用户");
        } else if (tiUsers.getUserState() == 1) {
            throw new LockedAccountException("账号已被锁定，请联系管理员");
        }

        /**
         * 返回用户对象 密码 加密后的加盐 realm 名称
         */
        return new SimpleAuthenticationInfo(tiUsers, tiUsers.getUserPassword(), ByteSource.Util.bytes(tiUsers.getSalt()), getName());
    }
}
